from io import BytesIO

import requests
from PIL import Image
import random
import string

def split_and_save_image(image_url,taskId):
    #生成一个20位随机字母数字组合的图片名
    response = requests.get(image_url, stream=True)
    #下载进度
    #提取链接第4和第五个/之间的内容作为图片名
    image_name=taskId
    total_size = int(response.headers['content-length'])
    print("图片大小：",total_size)
    print("开始下载图片")
    temp_size = 0
    with open('Static/big_img/'+f'{image_name}.jpg', 'wb') as file:
        for data in response.iter_content(chunk_size=1024):
            temp_size += len(data)
            file.write(data)
            done = int(50 * temp_size / total_size)
            # print("\r[%s%s]" % ('█' * done, ' ' * (50 - done)), end='')
            #增加百分比
            # print("已下载：%.2f%%" % float(temp_size / total_size * 100), end='')
    print("\n图片下载完成")

    with open('Static/big_img/'+f'{image_name}.jpg', 'rb') as file:
        image = Image.open(BytesIO(file.read()))

    # 获取图片的宽度和高度
    width, height = image.size

    # 定义子图的尺寸
    sub_width = width // 2
    sub_height = height // 2

    # 分割图片并保存子图
    sub_images = []
    for i in range(2):
        for j in range(2):
            left = j * sub_width
            upper = i * sub_height
            right = left + sub_width
            lower = upper + sub_height
            sub_image = image.crop((left, upper, right, lower))
            sub_image_file = 'Static/down_img/'+f"{image_name}_{i}{j}.jpg"
            sub_image.save(sub_image_file)
            sub_images.append('http://127.0.0.1:8000/' + sub_image_file)
            #保存在img文件夹下

    # 返回大图和子图的文件链接
    return 'image_file', sub_images